/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.workflow.repository;

import me.zhengjie.modules.workflow.domain.ActRuTask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

/**
* @website https://el-admin.vip
* @author wzp
* @date 2021-05-08
**/
public interface ActRuTaskRepository extends JpaRepository<ActRuTask, String>, JpaSpecificationExecutor<ActRuTask> {

    /**
     * 查询用户待办任务
     * 直接分配的任务 + 等待签收的任务
     * @param pageable
     * @return
     */
    @Query(value = "select RES.* from (" +
            "select distinct RES.ID_,RES.REV_,RES.EXECUTION_ID_,RES.PROC_INST_ID_,RES.PROC_DEF_ID_,RES.NAME_,RES.PARENT_TASK_ID_,RES.DESCRIPTION_,RES.TASK_DEF_KEY_,RES.OWNER_,RES.ASSIGNEE_,RES.DELEGATION_,RES.PRIORITY_,RES.CREATE_TIME_,RES.DUE_DATE_,RES.CATEGORY_,RES.SUSPENSION_STATE_,RES.TENANT_ID_,RES.FORM_KEY_,RES.CLAIM_TIME_ from ACT_RU_TASK RES where RES.ASSIGNEE_ = ?1 " +
            "union select distinct RES1.* from ACT_RU_TASK RES1 inner join ACT_RU_IDENTITYLINK I " +
            "on I.TASK_ID_ = RES1.ID_ where RES1.ASSIGNEE_ is null and I.TYPE_ = 'candidate' and ( I.USER_ID_ = ?1 ) or ( I.GROUP_ID_ IN(?2) )" +
            ") RES ",
            nativeQuery = true,countQuery = "select count(s1.ID_) from (" +
            "select distinct RES.ID_ from ACT_RU_TASK RES where RES.ASSIGNEE_ = ?1 " +
            "union select distinct RES1.* from ACT_RU_TASK RES1 inner join ACT_RU_IDENTITYLINK I " +
            "on I.TASK_ID_ = RES1.ID_ where RES1.ASSIGNEE_ is null and I.TYPE_ = 'candidate'and ( I.USER_ID_ = ?1 ) or ( I.GROUP_ID_ IN(?2) )" +
            ") s1")
    Page<ActRuTask> findTodoTask(String userId,String groupIds, Pageable pageable);

}